package com.eian.boot.security.handler;

import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.exception.NotPermissionException;
import com.eian.boot.common.core.model.CommonResult;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 安全相关全局异常处理器
 *
 * <p>处理 SaToken 相关的认证和授权异常,并返回符合 RESTful 规范的 HTTP 状态码
 *
 * @author alex.meng
 */
@Slf4j
@Order(70)
@RestControllerAdvice
public class SecurityGlobalExceptionHandler {

    /**
     * 处理未登录异常
     * 返回 HTTP 401 Unauthorized
     */
    @ExceptionHandler({NotLoginException.class})
    public ResponseEntity<CommonResult<Void>> handleNotLoginException(NotLoginException e, HttpServletRequest request) {
        String requestUri = request.getRequestURI();
        log.error("请求API'{}',登录状态异常：{}", requestUri, e.getMessage(), e);
        CommonResult<Void> result = CommonResult.fail(HttpStatus.UNAUTHORIZED.value(), "登录过期，请重新登录！");
        return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(result);
    }

    /**
     * 处理权限不足异常
     * 返回 HTTP 403 Forbidden
     */
    @ExceptionHandler({NotPermissionException.class})
    public ResponseEntity<CommonResult<Void>> handleNotPermissionException(NotPermissionException e, HttpServletRequest request) {
        String requestUri = request.getRequestURI();
        log.error("请求API'{}',权限检查异常：{}", requestUri, e.getMessage(), e);
        CommonResult<Void> result = CommonResult.fail(HttpStatus.FORBIDDEN.value(), "权限不足，无法访问！");
        return ResponseEntity.status(HttpStatus.FORBIDDEN).body(result);
    }
}